//
//  CZComposeViewController.swift
//  weibo27
//
//  Created by mac on 16/4/22.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class CZComposeController: UIViewController {

    var userStstusViewModel: CZUserStatusViewModel?
    // 照片选择器的孔子器
    private lazy var picturePickerView  = PictureCollectionVC()
    
    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView  { [weak self](emoticon) -> () in
        
        self?.textView.insertEmotion(emoticon)
    }
    
    override func loadView() {
        view = UIView()

        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        view.backgroundColor = UIColor.whiteColor()
        //键盘frame变化的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)

    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if picturePickerView.view.bounds.height == 0{
            textView.becomeFirstResponder()
        }
        
        
    }
    
    //点击关闭按钮时的方法
    @objc private func closeCompose(){
        
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    //点击发送按钮时的方法
    @objc private func sendMessage(){

        //键盘收起
        textView.resignFirstResponder()
        
        SVProgressHUD.show()
        
        let text = textView.emotionText()
        
        let image = UIImage(named: "datu")
        
        NetTools.shareTools.sendStatus(text,image: image) { (result, error) -> () in
            if error != nil{
                SVProgressHUD.showInfoWithStatus("你的网络不给力, 请稍后加载!")
                
                SVProgressHUD.dismiss()
            }
            
//            self.closeCompose()
            
            //界面跳到首页，并加载数据
           self.dismissViewControllerAnimated(false, completion: { () -> Void in
            //刷新数据
            
              SVProgressHUD.dismiss()
            
              NSNotificationCenter.defaultCenter().postNotificationName("sendStatusToWeibo", object: nil)
               SVProgressHUD.showInfoWithStatus("消息发送中....")
           })
        }
        
    }
    
    
    
    @objc private func selectPicture(){
        
        //隐藏键盘
        textView.resignFirstResponder()
        
        //如果照片视图已经出现，就不需要在重复的重置约束条件
        if picturePickerView.view.bounds.height>0{
            return
        }
        //在这里跟新控件的约束
        picturePickerView.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height*0.6)
        }
        //修改文本视图的约束 ‘重建约束’将以前的约束都清空重新建
        textView.snp_remakeConstraints { (make) -> Void in
            
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.bottom.equalTo(picturePickerView.view.snp_top)
            make.right.equalTo(view.snp_right)
        }
       
    }
    
    //选择表情按钮时的方法
    @objc private func selectEmoticon(){
        
//        print("撰写按钮被点击了")
        
        //1 让系统的键盘收回
        textView.resignFirstResponder()
        //2 设置表情键盘
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        //3 激活自定义的键盘
        textView.becomeFirstResponder()
    }
    
    let toolbar:UIToolbar = UIToolbar()
    
    private lazy var textView:UITextView = {
    
        let text = UITextView()
        
        text.font = UIFont.systemFontOfSize(18)
        
        text.textColor = UIColor.darkGrayColor()
        
        text.alwaysBounceVertical = true
        
        //退拽退出键盘
        text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 设置文本视图的代理
        text.delegate = self
        
        return text
    }()
    

    
    //站位文本
    private lazy var placeHoder:UILabel = UILabel(title: "分享微博...", fontSize: 18, color: UIColor.lightGrayColor())
    
    //注册一个监听键盘变化的通知
    func keyBoardChange(note: NSNotification){
        // 1键盘中的frame中的结构体是NSValue类型的
        let rec = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

        //2 变化的坐标
        let offset = -UIScreen.mainScreen().bounds.height + rec.origin.y
        
        //3 更新约束
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        //获取动画曲线
        let curve = (note.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
//        print(note)
        
        //4 获取动画时长UIKeyboardAnimationDurationUserInfoKey
        let duration = (note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //设置动画时长
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
            
            //设置动画的曲线
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
        }
        
    }
}

extension CZComposeController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        placeHoder.hidden = textView.hasText()
    }
}


extension CZComposeController{
    func setupUI(){
        
        //取消自动调整滚动视图的间距
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.whiteColor()
        
        titleNavigation()
        
        //添加textView文本框
        prepareTextView()
        //上传图片的
        prepareForPicture()
    }
    
    func prepareForPicture(){
        
        //如果添加的是一个控制器，要加上这一句
        addChildViewController(picturePickerView)
        
        // 添加视图
        view.insertSubview(picturePickerView.view, belowSubview: toolbar)
        
        // 设置frame
        picturePickerView.view.snp_makeConstraints { (make) -> Void in

           make.left.equalTo(view.snp_left)
           make.right.equalTo(view.snp_right)
           make.bottom.equalTo(view.snp_bottom)
           make.height.equalTo(0)
            
        }
        
    }
    
    //添加站位文本
    func prepareTextView(){
        
        view.addSubview(textView)
        textView.addSubview(placeHoder)
        
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.bottom.equalTo(toolbar.snp_top)
            make.right.equalTo(view.snp_right)
            
        }
        
        placeHoder.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
            
        }
        
        //更新UI
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    func titleNavigation(){
        //1 添加返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "closeCompose")
        
        //添发送回按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendMessage")
        navigationItem.rightBarButtonItem?.enabled = false
        
         let  nameLabel:UILabel = UILabel(title: CZUserAccountViewModel.shareModel.account?.screen_name ?? "",
            fontSize: 14, color: UIColor.lightGrayColor())
        
        let  titleLabel:UILabel = UILabel(title: "发送微博", fontSize: 15)
        
        //使用系统自带的头部
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        
        
        titleView.addSubview(nameLabel)
        titleView.addSubview(titleLabel)
        view.addSubview(toolbar)
        
        
        //2 设置布局
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        toolbar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        // 3 
        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName": "selectEmoticon" ],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        //遍历
        for dict in itemSettings{
            
            let item = UIBarButtonItem(imageName: dict["imageName"]!, actionName: dict["actionName"], target: self)
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
            
        }
        
        items.removeLast()
        
        toolbar.items = items
    }
}


































